package com.elcl.widget.comp.toast;

import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import com.elcl.storage.ApplicationCache;
import com.elcl.util.thread.ThreadPoolUtils;

public class ToastUtils {

    private static String old_msg = "";
    private static Handler handler = new Handler(Looper.getMainLooper());
    private static Object synObj = new Object();

    public static void showBaseToast(final String msg, final int time) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (synObj) { //加上同步是为了每个toast只要有机会显示出来
                    if (!old_msg.equals(msg)) {
                        StartClear();
                        MToast mToast = new MToast(ApplicationCache.context);
                        mToast.setDuration(time);
                        mToast.setView(msg, Gravity.CENTER);
                        old_msg = msg;
                    }
                }
            }
        });
    }

    public static void showToast(final String msg) {
        showBaseToast(msg, Toast.LENGTH_SHORT);
    }


    public static void showLongToast(String msg) {
        showBaseToast(msg, Toast.LENGTH_LONG);
    }

    public static void showToast(int resId) {
        String msg = ApplicationCache.context.getResources().getString(resId);
        showToast(msg);
    }

    public static void showLongToast(int resId) {
        String msg = ApplicationCache.context.getResources().getString(resId);
        showLongToast(msg);
    }

    private static void StartClear() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                old_msg = "";
            }
        });
    }


//	if (toast != null) {
//						//toast.cancel();
//						toast.setText(msg);
//						toast.setDuration(len);
//					} else {
//						toast = Toast.makeText(BaseApplication.getInstance().getApplicationContext(), msg, len);
//					}
//					toast.show();

}
